<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="质检项名称" prop="itemName">
              <el-input v-model="formData.itemName" placeholder="请输入质检项名称" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质检项分类" prop="itemType">
              <el-select v-model="formData.itemType" placeholder="请选择质检项分类" width="100%" filterable style="width: 100%"
                @change="handleItemTypeChange">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUALITY_INSPECTION_SCHEME_ITEM_TYPE)"
                  :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数值类型" prop="itemDataType">
              <el-select v-model="formData.itemDataType" placeholder="请选择数值类型" filterable style="width: 100%">
                <el-option v-for="item in itemDataTypeMap" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录入方式" prop="inputMethod">
              <el-select v-model="formData.inputMethod" placeholder="请选择录入方式" filterable style="width: 100%">
                <el-option v-for="item in inputMethodMap" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="不良判定方式" prop="defectMethod">
              <el-select v-model="formData.defectMethod" placeholder="请选择不良判定方式" filterable style="width: 100%">
                <el-option v-for="item in defectMethodMap" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标准值" prop="otherDefect">
              <el-input v-model="formData.otherDefect" placeholder="请输入标准值" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上公差" prop="upperValue">
              <el-input v-model="formData.upperValue" placeholder="请输入上公差" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下公差" prop="lowerValue">
              <el-input v-model="formData.lowerValue" placeholder="请输入下公差" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下警戒值" prop="lowerBias">
              <el-input v-model="formData.lowerBias" placeholder="请输入下警戒值" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上警戒值" prop="upperBias">
              <el-input v-model="formData.upperBias" placeholder="请输入上警戒值" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="SPC坐标" prop="excelCoordinate">
              <el-input v-model="formData.excelCoordinate" placeholder="请输入SPC坐标" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检验默认值" prop="defaultValue">
              <el-input v-model="formData.defaultValue" placeholder="请输入检验默认值" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="SPC检" prop="spcInspection">
              <el-input v-model="formData.spcInspection" placeholder="请输入SPC检" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="全尺寸检" prop="fullSizeInspection">
              <el-input v-model="formData.fullSizeInspection" placeholder="请输入全尺寸检" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="全尺寸坐标" prop="fullSizeCoordinate">
              <el-input v-model="formData.fullSizeCoordinate" placeholder="请输入全尺寸坐标" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="量具坐标" prop="toolCoordinate">
              <el-input v-model="formData.toolCoordinate" placeholder="请输入量具坐标" width="100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件名称代码" prop="failNameCode">
              <el-input v-model="formData.failNameCode" placeholder="请输入文件名称代码" width="100%" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="排序字段" prop="sort">-->
<!--              <el-input v-model="formData.sort" placeholder="请输入排序字段" width="100%" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <!-- <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status" width="100%">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="parseInt(dict.value)"
                  :label="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="不良原因" prop="badReasons">
              <el-select 
                v-model="formData.badReasons" 
                placeholder="请选择不良原因" 
                multiple 
                filterable 
                remote 
                reserve-keyword
                :remote-method="remoteBadReasonMethod"
                :loading="badReasonLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in badReasonList"
                  :key="item.id"
                  :label="item.badName"
                  :value="item.badName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="formData.memo" placeholder="请输入备注" type="textarea" width="100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as SchemeItemApi from '@/api/quality/schemeitem';
import * as BadReasonApi from '@/api/quality/badreason';
import { getDictDatas, DICT_TYPE } from '@/utils/dict';
export default {
  name: "SchemeItemForm",
  components: {
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 不良原因相关数据
      badReasonList: [],
      badReasonLoading: false,
      // 数值类型映射数组
      itemDataTypeMap: [
        { label: '字符(外观)', value: 1 },
        { label: '数字', value: 2 },
        { label: '日期', value: 3 },
        { label: '是/否', value: 4 },
        { label: '字符(功能)', value: 5 }
      ],
      // 录入方式映射数组
      inputMethodMap: [
        { label: '无', value: 0 },
        { label: '手工录入', value: 1 },
        { label: '按标准值校验', value: 2 }
      ],
      // 不良判定方式映射数组
      defectMethodMap: [
        { label: '无', value: 0 },
        { label: '手工输入', value: 1 },
        { label: '枚举选择', value: 2 }
      ],
      // 表单参数
      formData: {
        id: undefined,
        itemName: undefined,
        itemType: undefined,
        itemTypeName: undefined,
        itemDataType: undefined,
        inputMethod: undefined,
        otherDefect: undefined,
        upperValue: undefined,
        lowerValue: undefined,
        lowerBias: undefined,
        upperBias: undefined,
        excelCoordinate: undefined,
        defaultValue: undefined,
        spcInspection: undefined,
        fullSizeInspection: undefined,
        fullSizeCoordinate: undefined,
        toolCoordinate: undefined,
        failNameCode: undefined,
        defectMethod: undefined,
        badReasons: [],
        memo: undefined,
        sort: undefined,
        status: '1'
      },
      // 表单校验
      formRules: {
        itemName: [{ required: true, message: '质检项名称不能为空', trigger: 'blur' }],
        itemType: [{ required: true, message: '质检项分类不能为空', trigger: 'change' }],
        itemTypeName: [{ required: true, message: '质检项分类名称不能为空', trigger: 'blur' }],
        itemDataType: [{ required: true, message: '数值类型不能为空', trigger: 'change' }],
        inputMethod: [{ required: true, message: '录入方式不能为空', trigger: 'change' }],
        defectMethod: [{ required: true, message: '不良判定方式不能为空', trigger: 'change' }],
        sort: [{ required: true, message: '排序字段不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
      },
    };
  },
  methods: {
    /** 获取映射标签 */
    getMapLabel(value, mapArray) {
      const item = mapArray.find(item => item.value === value);
      return item ? item.label : value;
    },

    /** 处理质检项分类变化 */
    handleItemTypeChange(value) {
      const dictData = this.getDictDatas(DICT_TYPE.QUALITY_INSPECTION_SCHEME_ITEM_TYPE);
      const item = dictData.find(dict => parseInt(dict.value) === value);
      if (item) {
        this.formData.itemTypeName = item.label;
      }
    },

    /** 不良原因远程搜索 */
    async remoteBadReasonMethod(query) {
        this.badReasonLoading = true;
        try {
          const params = {
            pageNo: 1,
            pageSize: 20,
            badName: query
          };
          const res = await BadReasonApi.getBadReasonPage(params);
          this.badReasonList = res.data.list || [];
        } catch (error) {
          console.error('搜索不良原因失败:', error);
          this.badReasonList = [];
        } finally {
          this.badReasonLoading = false;
        }
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      this.remoteBadReasonMethod('')
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await SchemeItemApi.getSchemeItem(id);
          this.formData = res.data;
          this.dialogTitle = "修改质检项";
          // 如果有itemType，获取并设置itemTypeName
          if (this.formData.itemType) {
            this.handleItemTypeChange(this.formData.itemType);
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增质检项";
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await SchemeItemApi.updateSchemeItem(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await SchemeItemApi.createSchemeItem(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        itemName: undefined,
        itemType: undefined,
        itemTypeName: undefined,
        itemDataType: undefined,
        inputMethod: undefined,
        otherDefect: undefined,
        upperValue: undefined,
        lowerValue: undefined,
        lowerBias: undefined,
        upperBias: undefined,
        excelCoordinate: undefined,
        defaultValue: undefined,
        spcInspection: undefined,
        fullSizeInspection: undefined,
        fullSizeCoordinate: undefined,
        toolCoordinate: undefined,
        failNameCode: undefined,
        defectMethod: undefined,
        badReasons: [],
        memo: undefined,
        sort: undefined,
        status: 1
      };
      this.resetForm("formRef");
    }
  }
};
</script>
